//
//  ParserMRINFO.java
//  TopoManipApplet
//
//  Created by Thibaud PIQUET on 29/03/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

package src.convertisseur;
import src.convertisseur.Resume;
import java.util.*;
import java.io.*;
import org.jdom.*;
import org.jdom.Document;

/**
 *
 * @author Thibaud PIQUET
 */
public class ParserMRINFO implements Runnable{
    File ftp; // File to parse
	File fileOut; // File to create
    Reader frNode; // File Reader Node
    Reader frLink; // File Reader Link
    BufferedReader brNode; // Buffer Reader Node
    BufferedReader brLink; // Buffer Reader Link
    String line, line2;
    String chaine;
    String[] res;
	
    public ParserMRINFO(File file, File fileOUT) throws IOException {
        this.ftp = file;
		this.fileOut = fileOUT;
        this.frNode = new FileReader(this.ftp);
        this.brNode = new BufferedReader(this.frNode);
    }
	
	public void run() {
		try {
			this.parseToXML();
		}
		catch (Exception e) {
			e.printStackTrace();
			Resume result = Resume.getInstance();
			result.add("ParserMRINFO","procedure run had some problems : "+e);
		}
	}
    
	public void parseToXML() throws IOException {
		
        Element domain = new Element("domain");
		Element information = new Element("information");
        Element topology = new Element("topology");
		Element nodes = new Element("nodes");
        Element node = new Element("node");
		Element links = new Element("links");
        Element interfacesNode = new Element("interfaces");
        Element interfaceNode = new Element("interface");
        Element ip = new Element("ip");
        org.jdom.Document document = new Document(domain);
		
		Resume result = Resume.getInstance();

		try {
			line = this.brNode.readLine();
			
			Element title = new Element("title");
			Element date = new Element("date");
			Element author = new Element("author");
			Element description = new Element("description");
			Date today = new Date();
			String day = "";
			String month = "";
			
			title.setText(fileOut.getName());
			if(today.getDate()<10) { day = "0"+today.getDate();} else { day = today.getDate()+""; }
			if((today.getMonth()+1)<10){ month = "0"+(today.getMonth()+1);} else { month = (today.getMonth()+1)+"";}
			date.setText((today.getYear()+1900)+"-"+month+"-"+day);
			author.setText("File Generator");
			description.setText("File generated by ParserMRINFO from this jApplet");
			
			information.addContent(title);
			information.addContent(date);
			information.addContent(author);
			information.addContent(description);
			
			String state = "newNode";
			int counterInterface = 0;
			boolean BoolNodeExists = false;
			int counterInterfaceIfNodeExists = 0;
			boolean BoolLinkExists = false;
			
			Vector<String> tabIdLink = new Vector<String>();    // test to see if link already exists
			// we can't proceed the same way for node because, if node already exists, we have to modify it
			
			/* Node */
			Element switchNode;
			Element statusNode;
			Element NodeDescription;
			
			/* Link */
			Element link;
			Element source;
			Element target;
			Element bandwidth;
			Element statusLink;
			
			
			
			while (line!=null){
				if (line!=null){
					if(!line.startsWith("  ") && line.contains(":")) {
						if(state.equals("newNode")) {
							// description node line
							
							res = line.split(" ");
							// res[0] : ip node = label name too
							// res[1] : domain but we have to remove ()
							// res[2] : version
							
							
							List listOfNode = nodes.getChildren();
							Iterator ilistOfNode = listOfNode.iterator();
							while(ilistOfNode.hasNext()){
								Element currentNode = (Element)ilistOfNode.next();
								
								if(currentNode.getAttributeValue("id").equals(res[0])) {
									node = currentNode;
									interfacesNode = currentNode.getChild("interfaces");
									BoolNodeExists = true;
									result.add("ParserMRINFO","Node "+res[0]+" had 2 entries, they have been merged");
									counterInterfaceIfNodeExists = interfacesNode.getChildren().size();
								}
							}
							
							if(BoolNodeExists==false){
								node = new Element("node");
								Attribute id = new Attribute("id",res[0]);
								
								statusNode = new Element("status");
								statusNode.setText("UP");
								
								switchNode = new Element("switch");
								switchNode.setText("false");
								
								node.setAttribute(id);
								
								NodeDescription = new Element("description");
								Attribute label = new Attribute("label",res[0]);
								
								NodeDescription.setAttribute(label);
								node.addContent(NodeDescription);
								
								node.addContent(statusNode);
								node.addContent(switchNode);
								
								interfacesNode = new Element("interfaces");
							}
							
							state = "interfaces";
							
						}
						else if(state.equals("interfaces")) {
							if(BoolNodeExists==false){
								if(interfacesNode.getChildren().isEmpty()==false) {
									node.addContent(interfacesNode);
								}
								nodes.addContent(node);
								state="newNode";
								counterInterfaceIfNodeExists = 0;
								BoolNodeExists=false;
								counterInterface=0;
							}
							
							if(BoolNodeExists==true){
								state="newNode";
								counterInterfaceIfNodeExists = 0;
								BoolNodeExists=false;
								counterInterface=0;
							}
							
							res = line.split(" ");
							
							List listOfNode = nodes.getChildren();
							Iterator ilistOfNode = listOfNode.iterator();
							while(ilistOfNode.hasNext()){
								Element currentNode = (Element)ilistOfNode.next();
								
								if(currentNode.getAttributeValue("id").equals(res[0])) {
									node = currentNode;
									interfacesNode = currentNode.getChild("interfaces");
									BoolNodeExists = true;
									result.add("ParserMRINFO","Node "+res[0]+" had 2 entries, they have been merged");
									counterInterfaceIfNodeExists = interfacesNode.getChildren().size();
								}
							}
							
							if(BoolNodeExists==false){
								node = new Element("node");
								Attribute id = new Attribute("id",res[0]);
								
								switchNode = new Element("switch");
								switchNode.setText("false");
								
								statusNode = new Element("status");
								statusNode.setText("UP");
								
								node.setAttribute(id);
								
								NodeDescription = new Element("description");
								Attribute label = new Attribute("label",res[0]);
								
								NodeDescription.setAttribute(label);
								node.addContent(NodeDescription);
								
								node.addContent(statusNode);
								node.addContent(switchNode);
								interfacesNode = new Element("interfaces");
							}
							
							state = "interfaces";
							
						}
					}
					else if(line.startsWith("  ") && line.contains(">")) {
						if(state.equals("interfaces")) {
							res = line.split(" ");
							
							if(res[4].equals("0.0.0.0")) {
							}
							else if (res[4].startsWith("192.168")) {
							}
							else if (res[4].startsWith("10.")) {
							}
							else if (res[4].startsWith("169.")) {
							}
							else if(res[2].equals("0.0.0.0")) {
							}
							else if (res[2].startsWith("192.168")) {
							}
							else if (res[2].startsWith("10.")) {
							}
							else if (res[2].startsWith("169.")) {
							}
							else {
								interfaceNode = new Element("interface");
								if(BoolNodeExists==true){
									interfaceNode.setAttribute("id",counterInterfaceIfNodeExists+"");
									counterInterfaceIfNodeExists++;
								}
								else{
									interfaceNode.setAttribute("id",counterInterface+"");
								}
								ip = new Element("ip");
								
								ip.setAttribute("domain",res[5].replace("(","").replace(")",""));
								ip.setText(res[2]);
								
								interfaceNode.addContent(ip);
								interfacesNode.addContent(interfaceNode);
								counterInterface++;
								
								/* Links */
								
								BoolLinkExists = false;
								
								if(tabIdLink.contains(res[2]+"-"+res[4])){
									BoolLinkExists = true;
									result.add("ParserMRINFO","Link "+res[2]+"-"+res[4]+" had 2 entries, 1 has been deleted");
								}
								
								
								if(BoolLinkExists==false){
									link = new Element("link");
									Attribute idLink = new Attribute("id",res[2]+"-"+res[4]);
									tabIdLink.add(res[2]+"-"+res[4]);
									
									source = new Element("source");
									Attribute srcNode = new Attribute("node",res[2]);
									
									target = new Element("target");
									Attribute tgtNode = new Attribute("node",res[4]);
									
									statusLink = new Element("status");
									statusLink.setText("UP");
									
									source.setAttribute(srcNode);
									target.setAttribute(tgtNode);
									
									link.addContent(source);
									link.addContent(target);
									link.addContent(statusLink);
									
									if(res[5].contains("-ge") || res[5].contains("giga") || res[5].contains("GIGA")) {
										bandwidth = new Element("bandwidth");
										bandwidth.setText("1000000000");
										link.addContent(bandwidth);
									}
									else if(res[5].contains("-fast") || res[5].contains("-fe") || res[5].contains("-FE")) {
										bandwidth = new Element("bandwidth");
										bandwidth.setText("100000000");
										link.addContent(bandwidth);
									}
									
									link.setAttribute(idLink);
									links.addContent(link);
								}                             
							}
						}
					}
				}
				line = this.brNode.readLine();
			}
            
			brNode.close();
			frNode.close();
			
			topology.addContent(nodes);
			topology.addContent(links);
			
			domain.addContent(information);
			domain.addContent(topology);
			
			org.jdom.output.XMLOutputter sortie = new org.jdom.output.XMLOutputter(org.jdom.output.Format.getPrettyFormat());
			sortie.output(document, new FileOutputStream(fileOut.getAbsolutePath()));
			
			System.gc();
			
			result.add("ParserMRINFO","Import succeeded");
			
		} catch (Exception e) {
			e.printStackTrace();
			result.add("ParserMRINFO","Import had problems "+e);
		}
    }
}
